"""
读取movies和ratings，以movies数量作为矩阵x的列数
"""
import csv

from collaborative_filtering_recommandation import BASE_DIR
import numpy as np

def read_csv(path):
    data = []

    with open(path, "r", encoding="utf-8") as f:
        csv_reader = csv.reader(f)
        next(csv_reader)

        for row in csv_reader:
            data.append(row)

    return data


# movies数据里面有些列里包含了逗号，这些列数据用了双引号包裹了，这里要调整一下解析csv的代码
movies = read_csv(BASE_DIR / "data" / "ml-latest-small" / "movies.csv")
movies = np.array(movies)
ratings = read_csv(BASE_DIR / "data" / "ml-latest-small" / "ratings.csv")
ratings = np.array(ratings)

movie_id_index_map = {}
for i, movie_id in enumerate(movies[:, 0]):
    movie_id_index_map[movie_id] = i

user_id_dict = {}
for rating in ratings:
    user_id_dict[rating[0]] = None
user_id_list = list(user_id_dict.keys())

user_id_index_map = {}
for i, user_id in enumerate(user_id_list):
    user_id_index_map[user_id] = i

# user_movies_rating变量名太长了，随便叫个x
x = np.zeros((len(user_id_dict), len(movies)))
for rating in ratings:
    user_id = rating[0]
    user_index = user_id_index_map[user_id]

    movie_id = rating[1]
    movie_index = movie_id_index_map[movie_id]

    rating = rating[2]

    x[user_index][movie_index] = rating

x_dot = np.dot(x, x.T)
user_similarity = np.zeros((len(user_id_list), len(user_id_list)))
for i in range(len(user_id_list)):
    for j in range(len(user_id_list)):
        if i == j:
            continue

        user_similarity[i][j] = x_dot[i][j] / np.sqrt(x_dot[i][i] * x_dot[j][j])



user_similarity_sum = np.sum(user_similarity, axis=1, keepdims=True)

final_user_item_recommandation = np.dot(user_similarity, x) / user_similarity_sum


print(user_id_index_map)
print(movie_id_index_map)
print(final_user_item_recommandation[0])